package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 通用登录接口
     * POST /login
     * 参数：username, password, role
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");
        String role = credentials.get("role");

        Map<String, Object> result = new HashMap<>();

        Integer userType;
        if ("admin".equals(role)) {
            userType = 1;
        } else if ("doctor".equals(role)) {
            userType = 2;
        } else if ("patient".equals(role)) {
            userType = 3;
        } else {
            result.put("success", false);
            result.put("message", "无效的角色类型");
            return result;
        }

        User user = userService.login(username, password, userType);

        if (user != null) {
            result.put("success", true);
            result.put("message", role + "登录成功");
            result.put("userId", user.getId());
            result.put("realName",user.getRealName());
            // 根据角色你可以返回更多信息
        } else {
            result.put("success", false);
            result.put("message", "账号或密码错误");
        }

        return result;
    }
}
